package com.zzh.net.interceptor;


import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

import okhttp3.Connection;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.http.HTTP;

/**
 * http请求日志拦截器
 *
 * @author jacen
 * @data 2020/3/11 17:31
 * @email jacen@iswsc.com
 */
public class LogInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    public static final int MAX_LOG_BUFFER = 1024 * 1024;

    public enum Level {
        NONE,
        BASIC,
        HEADERS,
        BODY
    }

    public interface Logger {
        void log(String message);
    }

    private final Logger logger;

    public LogInterceptor(Logger logger) {
        this.logger = logger;
    }

    public LogInterceptor() {
        this.logger = new Logger() {
            @Override
            public void log(String message) {
                Log.i("JacenHttp", message);
            }
        };
    }

    private volatile Level level = Level.BODY;


    @Override
    public Response intercept(Chain chain) throws IOException {
        Level level = this.level;
        StringBuffer stringBuffer = new StringBuffer();
        Request request = chain.request();
        if (level == Level.NONE) {
            return chain.proceed(request);
        }

        boolean logBody = level == Level.BODY;
        boolean logHeaders = logBody || level == Level.HEADERS;

        RequestBody requestBody = request.body();
        boolean hasRequestBody = requestBody != null;
        String params = "";
        Connection connection = chain.connection();
        Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
        stringBuffer.append(request.method()).append(" ").append(protocol(protocol));
        if (!logHeaders && hasRequestBody) {
            stringBuffer.append(" (").append(requestBody.contentLength()).append("-byte body)");
        }
        if (logHeaders) {
            if (hasRequestBody) {
                // Request body headers are only present when installed as a network interceptor. Force
                // them to be included (when available) so there values are known.
                if (requestBody.contentType() != null) {
                    stringBuffer.append(" Content-Type: ").append(requestBody.contentType());
                }
                if (requestBody.contentLength() != -1) {
                    stringBuffer.append(" Content-Length: ").append(requestBody.contentLength());
                }
            }

            Headers headers = request.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                String name = headers.name(i);
                // Skip headers from the request body as they are explicitly logged above.
                if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                    stringBuffer.append(name).append(": ").append(headers.value(i));
                }
            }

            if (!logBody || !hasRequestBody) {
                stringBuffer.append("--> END ").append(request.method());
            } else if (bodyEncoded(request.headers())) {
                stringBuffer.append("--> END ").append(request.method()).append(" (encoded body omitted)");
            } else {
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);

                Charset charset = UTF8;
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }
                if (buffer.size() > MAX_LOG_BUFFER) {
                    params = " content too large ";
                } else {
                    params = buffer.readString(charset);
                }
                if (contentType != null && "multipart".equals(contentType.type())) {
                    int length = Math.min(params.length(), 1000);
                    params = params.substring(0, length);
                }
                stringBuffer.append(" --> END ").append(request.method()).append(" (").append(requestBody.contentLength()).append("-byte body)");
            }
        }
        logger.log("HTTP==request=info==" + request.url() + " params = 【" + params + "】" + stringBuffer.toString());

        StringBuffer sb = new StringBuffer();
        long startNs = System.nanoTime();
        Response response = chain.proceed(request);
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();
        String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
        int code = response.code();
        String url = response.request().url().toString();
        sb.append("HTTP==request==").append(url).append(" params = 【").append(params).append("】 ").append(code).append(" (").append(tookMs).append("ms) ").append("bodySize = ").append(bodySize);
        String content = "哇哦，没有返回结果";
        long bufferSize = 0;
        if (logHeaders) {
            Headers headers = response.headers();
            sb.append(" headers == ");
            for (int i = 0, count = headers.size(); i < count; i++) {
                sb.append(headers.name(i)).append(": ").append(headers.value(i)).append(", ");
            }
            logger.log(sb.toString());
            if (!logBody /*|| !HttpEngine.hasBody(response)*/) {
//                logger.log("<-- END HTTP");
            } else if (bodyEncoded(response.headers())) {
                logger.log("<--==END HTTP (encoded body omitted)");
            } else {
                BufferedSource source = responseBody.source();
                source.request(Long.MAX_VALUE); // Buffer the entire body.
                Buffer buffer = source.buffer();

                Charset charset = UTF8;
                MediaType contentType = responseBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }

                if (contentLength != 0) {
                    content = buffer.clone().readString(charset);
                    bufferSize = buffer.size();
                }
            }
            logger.log("HTTP==response=info== " + response.request().url() + " params = 【" + params + "】 \n result = 【" + content + "】 (" + bufferSize + "-byte body)");
        }
        return response;
    }

    private boolean bodyEncoded(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null && !"identity".equalsIgnoreCase(contentEncoding);
    }

    private static String protocol(Protocol protocol) {
        return protocol == Protocol.HTTP_1_0 ? "HTTP/1.0" : "HTTP/1.1";
    }

    public static boolean writeFile(String filePath, String content) {

        boolean success = false;
        FileOutputStream fos = null;
        try {
            File file = new File(filePath);
            if (file.getParentFile() != null && !file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            fos = new FileOutputStream(filePath);
            byte[] byteContent = content.getBytes();
            fos.write(byteContent);

            success = true;
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        } finally {

            try {

                if (fos != null) {
                    fos.close();
                }
            } catch (IOException ioe) {

                ioe.printStackTrace();
            }
        }

        return success;
    }
}
